import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Dec 11, 2006
 * Time: 10:12:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class MyCanvas extends Canvas implements Runnable
{
    public static final int desiredFPS = 10;
    public static final int desiredFrameTime = 1000 / desiredFPS;
    private int x;
    private long lastFrame;
    private long lastFrameTime;

    public MyCanvas()
    {
        x = 0;
        new Thread(this).start();
    }

    protected void paint(Graphics g)
    {
        g.setColor(0xffffff);
        g.fillRect(0, 0, 100, 100);
        g.setColor(0xff0000);
        g.fillRect(x, 20, 5, 5);
    }

    public void updateLogic()
    {
        x += 5;
        if (x >= 90)
            x = 0;
    }

    public void run()
    {
        lastFrame = System.currentTimeMillis();
        lastFrameTime = 0;
        while (true)
        {
            updateLogic();
            repaint();
            serviceRepaints();
            updateFPS();
        }
    }

    private void updateFPS()
    {
        long cFrame = System.currentTimeMillis();
        lastFrameTime = cFrame - lastFrame;
        lastFrame = cFrame;

        //don't bother if the diff is too small
        if (desiredFrameTime - lastFrameTime > 10)
        {
            try
            {
                Thread.sleep(desiredFrameTime - lastFrameTime);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }


    protected void showNotify()
    {
    }


    protected void hideNotify()
    {
    }
}
